<?php

function pre($arr)
{
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

class MysqlDb{
    private static $conn; //用来检测实例化有多少个
    private $table_prefix;
    static $link;  //用来查询时的链接资源

    // 连接数据库
    private function __construct($host, $user, $passwd, $db_name, $table_pre_fix){
        $this::$link = mysqli_connect($host, $user, $passwd, $db_name);
//        pre( $this::$link );die;
        $this->table_prefix = $table_pre_fix;
        if (!$this::$link) {
            die('连接数据库失败！');
        }

      //设置字符集
        mysqli_set_charset($this::$link, 'utf8');
    }

    /**
     * 查询多条数据
     */
    function selectAll($table_name, $ele = '*', $condition = '')
    {
        $sql = "SELECT {$ele} FROM $this->table_prefix{$table_name} {$condition}";

        $msg = mysqli_query($this::$link, $sql);
        // pre($sql);
        while ($res = mysqli_fetch_array($msg)) {
            $data_arr[] = $res;
        }
        return isset($data_arr) ? $data_arr : array();
    }

    // 查询一条记录
    function selectOne($table, $ele = '*', $condition = '')
    {
        $sql = "SELECT {$ele} FROM $this->table_prefix{$table} {$condition}";
        // pre($sql);
        $res = mysqli_query($this::$link, $sql);
        return mysqli_fetch_array($res);
    }

    // 添加到数据库
    function insert($sql){
        $res = mysqli_query($this::$link, $sql);
        if($res){
            return '添加成功！';
        }
    }


    // 更新到数据库
    function update($table_name, $value, $condition){
        $sql = "UPDATE `$this->table_prefix$table_name` SET $value $condition";
        // pre($sql);die;
        $res = mysqli_query($this::$link, $sql);
        return $res;
    }

     //从数据库删除记录
    function delData($table_name, $condition){

        // pre($sql);die;
        $path = $this->selectOne($table_name, '*', $condition);
        foreach($path as $val){
            if(is_file($val)){
                unlink($val);
            }
        }

        $sql = "DELETE FROM `$this->table_prefix$table_name` $condition";
        $res = mysqli_query($this::$link, $sql);

        return $res;
    }

    //防止克隆
    private function __clone(){}

    static function getInstance($host, $user, $passwd, $db_name, $table_pre_fix){
        if(!self::$conn instanceof self){
            return self::$conn = new self($host, $user, $passwd, $db_name, $table_pre_fix);
        }else{
            return self::$conn;
        }
    }

    function __destruct(){
       mysqli_close($this::$link);
    }
}


$current_url = pathinfo($_SERVER['PHP_SELF'])['basename'];
// pre($current_url);


/**
 * 获取当前URL
 */
function get_url()
{
    $url = $_SERVER['PHP_SELF'] . '?';
    if ($_GET) {
        foreach ($_GET as $k => $v) {
            if ($k != 'page') {
                $url .= "{$k}={$v}&";
            }
        }
    }
    return $url;
}

// 分页原理
function page($current, $count, $limit, $size, $class = '')
{
    $str = '';

    if ($count > $limit) {
        $pages = ceil($count / $limit);
        $url = get_url();

        $str = '<div class="pull-right"><ul class="$class" id="paginator-example">';
        if ($current == 1) {
            $str .= '<li><a>&lt;</a></li>';
        } else {
            $str .= "<li><a href='{$url}page=" . ($current - 1) . "'>&lt;</a></li>";
            $str .= "<li><a href='{$url}page=1'>首页</a></li>";
        }

        $compare = floor($size / 2);
        if ($current <= $compare) {
            $start = 1;
            $end = ($pages < $size) ? $pages : $size;

        } else if ($current > ($pages - $compare)) {
            $start = ($pages - $size + 1) < 1 ? 1 : ($pages - $size + 1);
            $end = $pages;

        } else {
            $start = $current - $compare;
            $end = $current + $compare;
        }

        for ($i = $start; $i <= $end; $i++) {
            if ($current == $i) {
                $str .= "<li class='active'><a>{$i}</a></li>";
            } else {
                $str .= "<li><a href='{$url}page={$i}'>{$i}</a></li>";
            }
        }

        if ($current == $pages) {
            $str .= '<li><a>&gt;</a></li>';
        } else {
            $str .= "<li><a href='{$url}page={$pages}'>尾页</a></li>";
            $str .= "<li><a href='{$url}page=" . ($current + 1) . "'>&gt;</a></li>";
        }

        $str .= "</ul></div>";
    }

    return $str;
}

// 下载上传的图片
function upload($name, $table_name, $file_dir='upload'){
    // 1. 判断错误信息
    if($_FILES[$name]['error'] > 0){
        switch($_FILES[$name]['error']){
            case 1:
                return "文件大小超出了 upload_max_filesize 的值";
                break;
            case 2:
                return "上传的文件大小超出了MAX_FILE_SIZE指令的值";
                break;
            case 3:
                return "如果文件没有完全上传";
                break;
            case 4:
                return "没有指定上传文件";
                break;
            default:
                return "未知错误";
        }
    }

    $uploads = $file_dir.'/'.$table_name; //指定上传目录
    if(!is_dir($uploads)){
        mkdir($uploads, 0777, TRUE);
    }

    // 获取文件类型
    $type = explode('/', $_FILES[$name]['type']); // image/jpeg

    // 获取文件后缀
    $suffix = array_pop($type);

    // 允许上传的数据类型
    $allows = ['jpeg','jpg','png','gif','psd'];

    //判断上传的文件类型
    if(!in_array($suffix,$allows)){ //in_array检查数组中是否存在某个值
        return "不允许上传 {$suffix} 文件类型<br />";
    }

    // 指定文件名
    $new_name = date("YmdHis").mt_rand(100,999).'.'.$suffix;
    $path = $uploads.'/'.$new_name;


    if(move_uploaded_file($_FILES[$name]['tmp_name'], $path)){
        $up_info['code'] = 1;
        $up_info['path'] = $path;           //图片所在路径 + 文件名
        $up_info['dir'] = $uploads;         //所在的文件夹
        $up_info['new_name'] = $new_name;   //文件名
        $up_info['str_mark'] = strmark($path, '小酒窝', $new_name, $uploads);
        $up_info['img_mark'] = img_mark($path, './images/1.jpg', $new_name, $uploads);
        $up_info['msg'] = "上传图片成功!";
    }else{
        $up_info['code'] = 0;
        $up_info['msg'] = "上传图片失败!";

    }
    return $up_info;
}

// 缩略图
function thumb($img_addr, $width, $height, $img_name='', $path='thumb'){
    list($w, $h, $type) = getimagesize($img_addr);

    $type_arr = [1 => 'gif', 2 => 'jpeg', 3 => 'png'];//获得后缀

    $desc_str = 'imagecreatefrom'.$type_arr[$type];

    $desc_img = $desc_str($img_addr);//创建一个新图像

    $true_img = imagecreatetruecolor($width, $height);

    imagecopyresized($true_img, $desc_img, 0, 0, 0, 0, $width, $height, $w, $h);

    header("Content-Type:image/{$type_arr[$type]}");

    $show_str = 'image'.$type_arr[$type];

    $new_path = $path.'/thumb';//缩略图存放路径
    if($img_name != ''){
        if(!is_dir($new_path)){
            mkdir($new_path);
        }
        $thumb_name = 'thumb_'.$img_name;
        $show_str($true_img, $new_path.'/'.$thumb_name);
        return $new_path.'/'.$thumb_name;
    }else{
        $show_str($true_img);
    }

    imagedestroy($true_img);
}

// 文字水印
function strmark($img_path, $str='', $str_name='', $dir='strmark/'){
    list($w, $h, $type) = getimagesize($img_path); //拿到图片的宽、高和类型

    $types = [1 => 'gif', 2 => 'jpeg', 3 => 'png'];

    $image_cre = 'imagecreatefrom'.$types[$type]; //变量函数

    $pre_img = $image_cre($img_path); //原图

    $red = imagecolorallocate($pre_img, 255, 0, 0); //给图片上颜色

    $x = 50;//  距离左边50
    $y = 50;//  距离上边50

    // 添加文字
    imagettftext($pre_img, 50, 0, $x, $y, $red, 'fonts/STXINGKA.TTF', $str);

    // header("Content-Type:image/{$types[$type]}");

    $save = 'image'.$types[$type];

    $str_mark_dir = $dir.'/strmark/'; //保存路径
    if(!is_dir($str_mark_dir)){
        mkdir($str_mark_dir);
    }

    // 保存文字水印图片
    $save($pre_img, $str_mark_dir.'strmark'.$str_name);

    imagedestroy($pre_img);

    return $str_mark_dir.'strmark'.$str_name;
}

// 图片水印
function img_mark($ori_img, $water_img, $img_name='', $img_dir='imgmark/'){
    list($ori_w, $ori_h, $ori_type) = getimagesize($ori_img);
    list($wa_w, $wa_h, $wa_type) = getimagesize($water_img);

    $types = [1 => 'gif', 2 => 'jpeg', 3 => 'png'];

    $preimagecreate = 'imagecreatefrom'.$types[$ori_type];//原图
    $waterimagecreate = 'imagecreatefrom'.$types[$wa_type];//新图

    $pre_img = $preimagecreate($ori_img);
    $img_desc = $waterimagecreate($water_img);

    //水印图片的位置
    $x = 100;
    $y = 100;

    imagecopy($pre_img, $img_desc, 0, 0, $x, $y, 150, 102);

    // header("Content-Type:image/{$types[$ori_type]}");

    $water_img_dir = $img_dir.'/imgmark/';
    if(!is_dir($water_img_dir)){
        mkdir($water_img_dir);
    }

    $save = 'image'.$types[$ori_type];
    $save($pre_img, $water_img_dir.'imgmark'.$img_name);

    imagedestroy($pre_img);
    imagedestroy($img_desc);

    return $water_img_dir.'imgmark'.$img_name;
}